<?php
/**
 * EmailCode.php
 * 邮件验证码工具
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2018-08-04 07:41:09
 */

namespace App\Utils;
use App\Exceptions\NormalException;
use App\Jobs\SendEmail;
use App\Mail\VerifyCode as VerifyCodeMail;
use Illuminate\Support\Facades\Cache;

class EmailCode {

    /**
     * 验证码发送
     * @param   $email
     * @return  boolean
     */
    static function send($email){
        $code = rand(111111, 999999);
        Cache::put('email_code_'.$email, $code, 20);

        //队列发送邮件
        dispatch(new SendEmail($email, new VerifyCodeMail($code)));

        return true;
    }

    /**
     * 验证码检测
     * @param   $email 
     * @param   $code 
     * @return  boolean
     */
    static function verify($email, $code){
        if(\App::environment('local')){
            return true;
        }

        $rightCode = Cache::get('email_code_'.$email);
        if(!$rightCode){
            return false;
        }

        return $rightCode == $code;
    }
}
